﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace RbacPermissionManage.WebAPI.Controllers
{
    /// <summary>
    /// 文件上传控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadImageController : ControllerBase
    {
        //
        private readonly IWebHostEnvironment web;
        private readonly IConfiguration configuration;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="web"></param>
        /// <param name="configuration"></param>
        public UploadImageController(IWebHostEnvironment web, IConfiguration configuration)
        {
            this.web = web;
            this.configuration = configuration;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadAvatarAsync(IFormFile file)
        {
            //判断文件大小是否大于5000KB
            if (file.Length / 1024 > 5000)
            {
                throw new Exception("文件大小超出范围");
            }

            //文件名
            string fileExt = Path.GetExtension(file.FileName);
            string[] fileExts = configuration["FileExts"].Split(',');
            //判断文件后缀是否正确
            if(!fileExts.Contains(fileExt))
            {
                throw new Exception("后缀不对");
            }

            //目录路径  这段会自动创建每一级文件夹
            string DirPath = $"/images/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}/";
            //判断目录是否存在
            if (!Directory.Exists($"{web.WebRootPath}{DirPath}"))
            {
                Directory.CreateDirectory($"{web.WebRootPath}{DirPath}");
            }

            
            //创建一个四位数的随机数
            Random random= new Random();
            int randomNum = random.Next(1000, 9999);

            //生成新的文件名
            string newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-{randomNum}{fileExt}";
            
            //把文件放到文件流
            using(FileStream fs = new FileStream($"{web.WebRootPath}/{DirPath}/{newFileName}", FileMode.Create))
            {
                await file.CopyToAsync(fs);
            }
            return Ok(new
            {
                fileName = $"{DirPath}{newFileName}"
            });
        }
    }
}
